__author__ = 'Soul'

from Assigner import *
from Logger import *

class EngineReader:

    def read_seeds(self, filename, key_word):
        self.__filename__ = filename
        urllist = []
        from xml.etree import ElementTree

        try:
            tree = ElementTree.parse(self.__filename__)
            engines = tree.findall('Engine')
            for engine in engines:
                netloc = engine.get('netloc')
                encoding = engine.get('encode')
                if encoding == None or encoding == '':
                    encoding = 'utf8'
                tmlogin = engine.get('manul_login')
                manul_login = False
                if tmlogin:
                    import string
                    manul_login = tmlogin.lower() == 'true'

                base_url = ''
                controller = ''
                database = ''
                login_url = ''
                redirect_url = ''
                cookie_path = ''
                for item in engine.getchildren():
                    if item.tag == 'base_url':
                        base_url = item.text
                    if item.tag == 'controller':
                        controller = item.text
                    if item.tag == 'database':
                        database = item.text
                    if item.tag == 'login_url':
                        login_url = item.text
                    if item.tag == 'redirect_url':
                        redirect_url = item.text
                    if item.tag == 'cookie':
                        cookie_path = item.text

                import urllib
                wd = urllib.quote(key_word.encode(encoding))
                if '%s' in base_url:
                    base_url = base_url%(wd)

                urllist.append({
                    'url': base_url,
                    'controller': controller,
                    'intent': {
                        'db_key': database,
                        'manul_login': manul_login,
                        'login_url': login_url,
                        'redirect_url': redirect_url,
                        'cookie': cookie_path
                    }
                })

                Assigner.set_controller_map(netloc, controller)

        except Exception as err:
            logger.error('Template %s parse error' % (self.__filename__))
            logger.error(str(err))

        return urllist